package com.dingyh.shopwebbackground.controller;


import com.dingyh.shopwebbackground.entity.Banned;
import com.dingyh.shopwebbackground.entity.Business;
import com.dingyh.shopwebbackground.entity.Payouts;
import com.dingyh.shopwebbackground.entity.User;
import com.dingyh.shopwebbackground.service.BusinessService;
import com.dingyh.shopwebbackground.service.PayoutsService;
import com.dingyh.shopwebbackground.service.UserService;
import com.dingyh.shopwebbackground.util.CommonResult;
import com.dingyh.shopwebbackground.util.UUIDUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dingyuhan
 * @since 2023-02-13
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    BusinessService businessService;

    @Autowired
    PayoutsService payoutsService;

    /**
     * 通过id查找user
     * @param id
     * @param role
     * @return
     */
    @RequestMapping("/selectById")
    public CommonResult selectById(String id,String role){
        User user = userService.selectById(id, role);
        if(user.getRole().equals("2")){
            Business business = businessService.selectByUserId(user.getId());
            user.setAddressDetail(business.getAddressDetail());
            user.setProvince(business.getProvince());
            user.setCity(business.getCity());
            user.setArea(business.getArea());
        }
        if(user != null){
            return new CommonResult(200,"",user);
        }else{
            return new CommonResult(500,"您查找的用户不存在！");
        }
    }

    /**
     * 登录
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping("/getLogin")
    public CommonResult getLogin(String userName,String password){
        Map<String,Object> map = new HashMap<>();
        map.put("userName",userName);
        map.put("password",password);
        User user = userService.getLogin(map);
        if(user != null){
            if(user.getRole().equals("2")){
                Business business = businessService.selectByUserId(user.getId());
                user.setAddressDetail(business.getAddressDetail());
                user.setProvince(business.getProvince());
                user.setCity(business.getCity());
                user.setArea(business.getArea());
            }
            return new CommonResult(200,"登陆成功",user);
        }else{
            return new CommonResult(500,"账户密码错误，请重新输入",null);
        }
    }

//    @RequestMapping("/changeInformation")
//    public CommonResult changeInformation(String id,String nickname,String tel,String mail){
//        Map<String,Object> map = new HashMap<>();
//        map.put("id",id);
//        map.put("userName",nickname);
//        map.put("tel",tel);
//        map.put("mail",mail);
//        User user = userService.changeInformation(id,nickname,tel,mail);
//        if(user != null){
//            return new CommonResult(200,"修改成功",user);
//        }else{
//            return new CommonResult(500,"系统错误，请联系管理员",null);
//        }
//    }

    /**
     * 拿到user表
     * @param role
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("getAllUser")
    public CommonResult<Object> getAllUser(String role,
                                           @RequestParam(defaultValue = "1",required = true )int pageIndex, @RequestParam(defaultValue = "10",required = true )int pageSize){
        PageHelper.startPage(pageIndex, pageSize);//初始化分页
        Map<String,Object> map = new HashMap<>();
        map.put("role",role);
        List<User> users = userService.getAllUser(map);
        PageInfo<User> page = new PageInfo<>(users);
        return new CommonResult(200,"",page);
    }

    /**
     * 买家注册
     * @param user
     * @return
     */
    @RequestMapping("/registerUer")
    public CommonResult<Object> registerUer(User user){
        int countMail = userService.getByMail(user.getMail());
        int countTel = userService.getByTel(user.getTel());
        if (countTel > 0 ) {
            return new CommonResult<>(500, "该手机号已存在");
        }
        if (countMail > 0 ){
            return new CommonResult<>(500,  "该邮箱号已存在");
        }
        User userCurr = User.builder()
                .id(UUIDUtil.generator())
                .nickname(user.getNickname())
                .tel(user.getTel())
                .mail(user.getMail())
                .pwd(user.getPwd())
                .timeadd(System.currentTimeMillis())
                .avatar(user.getAvatar())
                .role(user.getRole())
                .disable("0")
                .build();
        boolean result = userService.save(userCurr);
        if (result) {
            return new CommonResult(200, "注册成功", null);
        } else {
            return new CommonResult(500, "注册失败", null);
        }
    }

    /**
     * 买家修改个人信息
     * @param user
     * @return
     */
    @RequestMapping("/updBuy")
    public CommonResult<Object> updBuy(User user, String isMoney){
        User curr = userService.getById(user.getId());
        boolean result = userService.updBuy(user);
        if( isMoney.equals("1") ){
            Payouts payouts = Payouts.builder()
                    .id(UUIDUtil.generator())
                    .source("2")
                    .state("2-1")
                    .timeadd(System.currentTimeMillis())
                    .money(user.getMoney().subtract(curr.getMoney()))
                    .timearrival(System.currentTimeMillis())
                    .build();
            if(payoutsService.save(payouts)){
            }
        }
        if(result ){
            return new CommonResult(200, "修改成功！", null);
        }else{
            return new CommonResult(500, "修改失败！", null);
        }
    }

    /**
     * 商家修改个人信息
     * @param user
     * @return
     */
    @RequestMapping("/updShop")
    public CommonResult<Object> updShop(User user, String saleLogo){
        if(userService.updShop(user, saleLogo)){
            return new CommonResult(200, "修改成功！", null);
        }else{
            return new CommonResult(500, "修改失败！", null);
        }
    }



    /**
     * 解除禁言
     * @param user
     * @return
     */
    @RequestMapping("/endBan")
    public CommonResult<Object> endBan(User user){
        if( userService.getByDisabled(user) > 0 ) {
            return new CommonResult(500, "当前用户无禁言状态！", null);
        }else if(userService.endBan(user)){
            return new CommonResult(200, "解除禁言成功！", null);
        }else{
            return new CommonResult(500, "解除禁言失败！", null);
        }
    }

    /**
     * 主页获取买家/卖家数量
     * @return
     */
    @RequestMapping("/getCount")
    public CommonResult<Object> getCount(){
        Integer userCount = userService.getUserCount();
        Integer saleCount = userService.getSaleCount();
        return new CommonResult(200, "获取数据成功！", new Integer[]{userCount, saleCount});
    }

    /**
     * 上传图片
     * @param file
     * @return
     */
    @RequestMapping("/uploadImageUser")
    public  CommonResult<Object> uploadImage(@RequestPart("file") MultipartFile file){
        String path = "D:/GraduatioProject/shopWeb-background/src/main/webapp/upload_images/user/";
        String picName = System.currentTimeMillis() + ".jpg";
        File targetFile = new File(path, picName);//文件地址-文件名字
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
//            e.printStackTrace();
            return new CommonResult<>(500,"",null);
        }
        return  new CommonResult<>(200,"", picName);
    }

}

